package com.pig4cloud.pig.ads.controller.gdt;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.ads.service.AdLandingPageService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.utils.DateUtils;
import com.pig4cloud.pig.ads.utils.HtmlRequest;
import com.pig4cloud.pig.ads.utils.ImgTagUtils;
import com.pig4cloud.pig.api.entity.AdLandingPage;
import com.pig4cloud.pig.api.gdt.entity.GdtXlp;
import com.pig4cloud.pig.api.gdt.vo.GdtXlpVo;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @ 蹊径落地页 前端控制器
 * @author yk
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/gdtXlp")
@Api(value = "GdtXlp", tags = "蹊径落地页管理模块")
public class GdtXlpController {

	private final AdvService advService;

	private final AdLandingPageService adLandingPageService;

	/**
	 * 分页查询落地页信息
	 * @return 分页对象
	 */
	@RequestMapping("/getPage")
	public R getPage(GdtXlpVo req) {
		//设置分页条件
		Page page = new Page();
		page.setSize(req.getSize());
		page.setCurrent(req.getCurrent());
		//获取到当前登录用户
		Integer id = SecurityUtils.getUser().getId();
		//通过登录用户去查询多个广告主id
		List<String> allList = advService.getOwnerAdv(id, PlatformTypeEnum.GDT.getValue());
		if(allList == null || allList.size() == 0) {
			return R.ok(new Page());
		}
		//设置where条件
		QueryWrapper<AdLandingPage> queryWrapper = new QueryWrapper<>();
		//查询所有
		queryWrapper.in("advertiser_id", allList);
		//根据广告主id查询
		String[] advArr = req.getAccountIds();
		if (advArr != null && advArr.length > 0) {
			List<String> selectList = Arrays.asList(advArr);
			if (!allList.containsAll(selectList)) {
				return R.failed("广告账户不可用");
			}
			queryWrapper.in("advertiser_id", selectList);
		}
		//根据落地页名称模糊查询
		String pageName = req.getPageName();
		if (!StringUtils.isBlank(pageName) ){
			queryWrapper.like("page_name",pageName);
		}
		//根据落地页id查询
		String pageId = req.getPageId();
		if (!StringUtils.isBlank(pageId)){
			queryWrapper.eq("page_id",pageId);
		}
		//根据最近更新时间降序
		queryWrapper.orderByDesc("last_modify_time");
		// 分页查询
		IPage<AdLandingPage> iPage = adLandingPageService.getLandingIPage(page, queryWrapper);

		// 重新组装返回对象
		IPage<GdtXlp> resultPage = new Page<>();
		BeanUtils.copyProperties(iPage,resultPage);
		List<GdtXlp> resultList = Lists.newArrayList();
		if (Objects.nonNull(iPage) && CollectionUtils.isNotEmpty(iPage.getRecords())){
			for (AdLandingPage adLandingPage : iPage.getRecords()){
				resultList.add(dealData(adLandingPage));
			}
		}
		resultPage.setRecords(resultList);
		return R.ok(resultPage, "操作成功");
	}

	//获取预览地址
	@RequestMapping("/preview")
	public R previewById(Integer id){
		if (Objects.isNull(id)) {
			return R.failed("id不允许为空");
		}
		AdLandingPage adLandingPage = adLandingPageService.getById(id);
		String url = adLandingPage.getPageUrl();
		return R.ok(url,"操作成功");
	}
	//根据id查询:修改时回显
	@RequestMapping("/findById")
	public R getById(Integer id){
		if (Objects.isNull(id)) {
			return R.failed("id不允许为空");
		}
		AdLandingPage adLandingPage = adLandingPageService.getById(id);
		GdtXlp gdtXlp = dealData(adLandingPage);
		gdtXlp.setPreviewUrl(adLandingPage.getPageUrl());
		return R.ok(gdtXlp,"操作成功");
	}

	/*
	*  @author: nml
	* */
	//解析preview_url，提取图片url
	public List<String> getImageUrl(String previewUrl) throws Exception{
		//根据字符串url创建URL
		URL url = new URL(previewUrl);
		//获取url的html源代码
		String html = HtmlRequest.getURLSource(url);
		//1、data-image
		//获取源代码中的 标签：img、属性：data-image
		List<String> list = ImgTagUtils.listTagPropertyValue(html, "img", "data-image");
		if (list.size()<=0){
			list = ImgTagUtils.listTagPropertyValue(html, "img", "src");
		}
		return list;
	}
	/**
	 * 20220318 落地页改造统一表，前段不改动 ，后端数据重组
	 * @param adLandingPage
	 * @return
	 */
	private GdtXlp dealData(AdLandingPage adLandingPage){
		if (Objects.nonNull(adLandingPage)) {
			GdtXlp xlp = new GdtXlp();
			xlp.setId(adLandingPage.getId());
			xlp.setPreviewUrl(adLandingPage.getPageUrl());
			xlp.setPageName(adLandingPage.getPageName());
			xlp.setPageId(adLandingPage.getPageId());
			xlp.setPageStatus(adLandingPage.getStatus());
			xlp.setPagePublishStatus(adLandingPage.getPublishStatus());
			xlp.setCreateTime(DateUtils.dateToString(adLandingPage.getCreateTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
			xlp.setPageServiceId(adLandingPage.getPageServiceId());
			xlp.setPageType(adLandingPage.getPageType());
			xlp.setPageLastModifyTime(Objects.nonNull(adLandingPage.getLastModifyTime()) ? DateUtils.dateToString(adLandingPage.getLastModifyTime(),DateUtils.YYYY_MM_DD_HH_MM_SS) : null);
			xlp.setAccountId(adLandingPage.getAdvertiserId());
			xlp.setPagePublishType(adLandingPage.getPlayableType());
			xlp.setPromotedObjectId(adLandingPage.getPromotedObjectId());
			xlp.setProductCatalogId(Objects.nonNull(adLandingPage.getProductCatalogId()) ? String.valueOf(adLandingPage.getProductCatalogId()) : null);
			//如果previewUrl不为空
			if (StringUtils.isNotBlank(adLandingPage.getPageUrl()) ){
				//解析
				try {
					List<String> imageUrl = getImageUrl(adLandingPage.getPageUrl());
					if (imageUrl.size()>0){
						//将第一个imageUrl设置为previewUrl
						xlp.setPreviewUrl(imageUrl.get(0));
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return xlp;
		}
		return null;
	}

/*	public static void main(String[] args) throws Exception{
		URL url = new URL("https://h5.gdt.qq.com/xjviewer/nemo/2525482?productType=38");
		String html = HtmlRequest.getURLSource(url);

		List<String> list = ImgTagUtils.listImgSrc(html);
		for (String str : list) {
			System.out.println(str);
		}
	}*/

}
